'use strict';

const Controller = require('egg').Controller;
const bcrypt = require('bcryptjs');
<<<<<<< HEAD
=======
const path = require('path');
const fs = require('fs');
const jwtUtils = require('../utils/jwt');
>>>>>>> resume

class AccountController extends Controller {
  // 用户注册
  async register() {
    const { ctx } = this;
<<<<<<< HEAD
    const { username, password, email } = ctx.request.body;
=======
    const { username, password, email, role } = ctx.request.body;
>>>>>>> resume

    // 验证参数
    if (!username || !password) {
      ctx.body = {
        success: false,
        code: 1,
        msg: '用户名和密码不能为空'
      };
      return;
    }

<<<<<<< HEAD
=======
    // 验证角色
    const validRoles = ['user', 'enterprise', 'admin'];
    const userRole = role || 'user';
    if (!validRoles.includes(userRole)) {
      ctx.body = {
        success: false,
        code: 1,
        msg: '无效的角色类型，可选: user, enterprise, admin'
      };
      return;
    }

>>>>>>> resume
    try {
      // 检查用户是否已存在
      const existingUser = await ctx.model.User.findOne({
        where: {
          username
        }
      });

      if (existingUser) {
        ctx.body = {
          success: false,
          code: 1,
          msg: '用户已存在'
        };
        return;
      }

<<<<<<< HEAD
=======
      // 处理头像上传
      let avatarPath = null;
      const file = ctx.request.files?.[0];
      if (file) {
        // 创建用户头像目录
        const userDir = path.join(this.config.baseDir, 'app/public/user');
        if (!fs.existsSync(userDir)) {
          fs.mkdirSync(userDir, { recursive: true });
        }

        // 生成唯一文件名
        const ext = path.extname(file.filename);
        const filename = `${Date.now()}_${Math.random().toString(36).substring(7)}${ext}`;
        const targetPath = path.join(userDir, filename);

        // 移动文件
        const reader = fs.createReadStream(file.filepath);
        const writer = fs.createWriteStream(targetPath);
        reader.pipe(writer);

        await new Promise((resolve, reject) => {
          writer.on('finish', resolve);
          writer.on('error', reject);
        });

        // 删除临时文件
        fs.unlinkSync(file.filepath);

        // 保存相对路径
        avatarPath = `/public/user/${filename}`;
      }

>>>>>>> resume
      // 密码加密
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(password, salt);

      // 创建新用户
      const user = await ctx.model.User.create({
        username,
        password: hashedPassword,
        email,
<<<<<<< HEAD
=======
        role: userRole,
        avatar: avatarPath,
>>>>>>> resume
        created_at: new Date(),
        updated_at: new Date()
      });

      ctx.body = {
        success: true,
        code: 0,
        msg: '注册成功',
        data: {
          id: user.id,
          username: user.username,
<<<<<<< HEAD
          email: user.email
=======
          email: user.email,
          role: user.role,
          avatar: user.avatar
>>>>>>> resume
        }
      };
    } catch (error) {
      ctx.body = {
        success: false,
        code: 1,
        msg: '注册失败: ' + error.message
      };
    }
  }

  // 用户登录
  async login() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;

    // 验证参数
    if (!username || !password) {
      ctx.body = {
        success: false,
        code: 1,
        msg: '用户名和密码不能为空'
      };
      return;
    }

    try {
      // 查找用户
      const user = await ctx.model.User.findOne({
        where: {
          username
        }
      });

      if (!user) {
        ctx.body = {
          success: false,
          code: 1,
          msg: '用户名或密码错误'
        };
        return;
      }

      // 验证密码
      const isMatch = await bcrypt.compare(password, user.password);
      if (!isMatch) {
        ctx.body = {
          success: false,
          code: 1,
          msg: '用户名或密码错误'
        };
        return;
      }

<<<<<<< HEAD
      // 生成token (实际项目中应该使用JWT)
      const token = `token_${user.id}_${Date.now()}`;
=======
      // 如果是企业角色，查询员工表获取企业ID
      let enterpriseId = null;
      if (user.role === 'enterprise') {
        // 通过用户名查找员工表（假设用户名与员工姓名匹配）
        const employee = await ctx.model.Employee.findOne({
          where: {
            employeeName: user.username,
            employeeStatus: 'active' // 只查找在职员工
          }
        });
        
        if (employee) {
          enterpriseId = employee.enterpriseId;
        }
      }

      // 使用JWT生成token
      const payload = {
        id: user.id,
        username: user.username,
        role: user.role,
        enterpriseId: enterpriseId // 添加企业ID到token
      };
      const token = jwtUtils.signToken(
        payload,
        this.config.jwt.secret,
        this.config.jwt.expiresIn
      );
>>>>>>> resume

      ctx.body = {
        success: true,
        code: 0,
        msg: '登录成功',
        data: {
          id: user.id,
          username: user.username,
          email: user.email,
<<<<<<< HEAD
=======
          role: user.role,
          avatar: user.avatar,
          enterpriseId: enterpriseId, // 返回企业ID
>>>>>>> resume
          token
        }
      };
    } catch (error) {
      ctx.body = {
        success: false,
        code: 1,
        msg: '登录失败: ' + error.message
      };
    }
  }

  // 用户登出
  async logout() {
    const { ctx } = this;
    
    // 实际项目中应该使token失效
    ctx.body = {
      success: true,
      code: 0,
      msg: '登出成功'
    };
  }
<<<<<<< HEAD
=======

  // 获取用户列表（管理员）
  async getUsers() {
    const { ctx } = this;
    const { page = 1, pageSize = 10, username, role } = ctx.query;

    try {
      const where = {};
      if (username) {
        where.username = { [ctx.app.Sequelize.Op.like]: `%${username}%` };
      }
      if (role) {
        where.role = role;
      }

      const { count, rows } = await ctx.model.User.findAndCountAll({
        where,
        attributes: ['id', 'username', 'email', 'role', 'avatar', 'created_at', 'updated_at'],
        limit: parseInt(pageSize),
        offset: (parseInt(page) - 1) * parseInt(pageSize),
        order: [['created_at', 'DESC']]
      });

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: rows,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(pageSize),
          total: count,
          pages: Math.ceil(count / parseInt(pageSize))
        }
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        message: '获取用户列表失败: ' + error.message,
        data: null
      };
    }
  }

  // 获取单个用户（管理员）
  async getUser() {
    const { ctx } = this;
    const { id } = ctx.params;

    try {
      const user = await ctx.model.User.findByPk(id, {
        attributes: ['id', 'username', 'email', 'role', 'avatar', 'created_at', 'updated_at']
      });

      if (!user) {
        ctx.body = {
          code: 404,
          message: '用户不存在',
          data: null
        };
        return;
      }

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: user
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        message: '获取用户失败: ' + error.message,
        data: null
      };
    }
  }

  // 创建用户（管理员）
  async createUser() {
    const { ctx } = this;
    const { username, password, email, role = 'user' } = ctx.request.body;

    try {
      if (!username || !password) {
        ctx.body = {
          code: 400,
          message: '用户名和密码不能为空',
          data: null
        };
        return;
      }

      // 检查用户是否已存在
      const existingUser = await ctx.model.User.findOne({ where: { username } });
      if (existingUser) {
        ctx.body = {
          code: 400,
          message: '用户名已存在',
          data: null
        };
        return;
      }

      // 加密密码
      const hashedPassword = await bcrypt.hash(password, 10);

      // 创建用户
      const user = await ctx.model.User.create({
        username,
        password: hashedPassword,
        email,
        role
      });

      ctx.body = {
        code: 201,
        message: '创建成功',
        data: {
          id: user.id,
          username: user.username,
          email: user.email,
          role: user.role
        }
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        message: '创建用户失败: ' + error.message,
        data: null
      };
    }
  }

  // 更新用户（管理员）
  async updateUser() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { username, email, role, password } = ctx.request.body;

    try {
      const user = await ctx.model.User.findByPk(id);
      if (!user) {
        ctx.body = {
          code: 404,
          message: '用户不存在',
          data: null
        };
        return;
      }

      const updateData = {};
      if (username) updateData.username = username;
      if (email !== undefined) updateData.email = email;
      if (role) updateData.role = role;
      if (password) {
        updateData.password = await bcrypt.hash(password, 10);
      }

      await user.update(updateData);

      ctx.body = {
        code: 200,
        message: '更新成功',
        data: {
          id: user.id,
          username: user.username,
          email: user.email,
          role: user.role
        }
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        message: '更新用户失败: ' + error.message,
        data: null
      };
    }
  }

  // 删除用户（管理员）
  async deleteUser() {
    const { ctx } = this;
    const { id } = ctx.params;

    try {
      const user = await ctx.model.User.findByPk(id);
      if (!user) {
        ctx.body = {
          code: 404,
          message: '用户不存在',
          data: null
        };
        return;
      }

      await user.destroy();

      ctx.body = {
        code: 200,
        message: '删除成功',
        data: null
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        message: '删除用户失败: ' + error.message,
        data: null
      };
    }
  }
>>>>>>> resume
}

module.exports = AccountController;